<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Register</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <style type="text/css">
        .account {
            width: 400px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div class="account">
        <h2 style="text-align: center">注册</h2>
        <form action="">
            {% for field in form %}
                {% if field.name == 'code' %}
                    <div class="form-group">
                        <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                        <div class="clearfix">
                            <div class="col-md-6" style="padding-left: 0;">{{ field }}</div>
                            <div class="col-md-6"><input id="code_btn" type="button" class="btn btn-default" value="点击获取验证码"></div>
                        </div>
                    </div>
                {% else %}
                    <div class="form-group">
                        <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                        {{ field }}
                    </div>
                {% endif %}
            {% endfor %}
            <button type="submit" class="btn btn-primary" value="注册">注册</button>
        </form>
  </div>


</body>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script>
    let code_btn = document.getElementById("code_btn");
    code_btn.addEventListener("click", getCode);
    function getCode() {
        let phone = checkPhone();
        if (phone){
            {#console.log(phone);#}
        {#    发送ajex请求 #}
            $.ajax({
                url: '/app01/get_code/',
                type: 'POST',
                data: {
                    tpl: 'register',
                    pNum: phone
                },
                success: function (data) {
                    if (data){
                        resetTime(document.getElementById("code_btn"));
                    }
                }

            })
        }

    }
    function checkPhone(){
    let phone = document.getElementById('id_mobile_phone').value;
    if(!(/^1[3456789]\d{9}$/.test(phone))){
        alert("手机号码有误，请重填");
        return false;
    }
    return phone;

    }

    function resetTime(e){
    let second = 60;
    let timer = null;
    timer = setInterval(function(){
        second -= 1;
        if(second >0){
            $(e).attr('disabled',true);
            e.value = second + "秒后获取验证码";
        }else{
            clearInterval(timer);
            $(e).attr('disabled',false);
            e.value = "点击获取验证码";
        }
    },1000);
    }

</script>
</html>